package com.cms.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.cms.model.Type;
import com.cms.service.TypeService;
import com.cms.service.TypeServiceImpl;


public class TypeManager {

	private static TypeManager instance = null;
	public static synchronized TypeManager getInstance()
	{
		if (instance == null)
		{
			instance = new TypeManager();
		}
		return instance;
	} 
	
	private TypeService service;
	private Map<String,Type> typeMap;
	private Object lock = new Object();
	
	private String maxId="0";
	
	protected TypeManager()
	{
		service = new TypeServiceImpl();
		typeMap = new HashMap<String, Type>();
		
		List<Type> tlist = service.getAll();
		if(tlist!=null&&tlist.size()>0)
		{
			for (Type type : tlist) {
				typeMap.put(type.getId(), new Type(type));
			}
			maxId = service.getMaxId();
		}
	}
	
	public List<Type> getAll()
	{
		List<Type> list = new ArrayList<Type>();
		for (Entry<String,Type> e : typeMap.entrySet()) {
			list.add(new Type(e.getValue()));
		}
		return list;
	}
	
	public Type getById(String id)
	{
		if(typeMap.containsKey(id))
			return new Type(typeMap.get(id));
		return null;
	}
	
	public boolean insert(Type t)
	{
		synchronized(lock)
		{
			t.setId((Integer.parseInt(maxId)+1)+"");
			if(service.insert(t))
			{
				maxId = (Integer.parseInt(maxId)+1)+"";
				typeMap.put(maxId, new Type(t));
				return true;
			}
		}
		return false;
	}
	
	public boolean update(Type t)
	{
		String id = t.getId();
		if(!typeMap.containsKey(id))
			return false;
		
		Type type = getById(t.getId());
		if(type==null || !type.getId().equals(t.getId()))
			return false;
		
		synchronized (lock) {
			if(service.update(t))
			{
				typeMap.get(id).setName(t.getName());
				typeMap.get(id).setRemark(t.getRemark());
				
				return true;
			}
		}
		return false;
	}
	
	public boolean delete(Type t)
	{
		String id = t.getId();
		if(!typeMap.containsKey(id))
			return false;
		
		synchronized (lock) {
			if(service.delete(t))
			{
				typeMap.remove(id);
				return true;
			}
		}
		return false;
	}
}
